package info.xingxingdd.admin.controller.foreground;

import info.xingxingdd.admin.common.Result;
import info.xingxingdd.admin.dto.LoginRequest;
import info.xingxingdd.admin.dto.LoginResponse;
import info.xingxingdd.admin.entity.ClientUser;
import info.xingxingdd.admin.service.ClientUserService;
import info.xingxingdd.admin.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final ClientUserService clientUserService;
    private final JwtUtil jwtUtil;
    private final RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 登录
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        // 根据用户名查询用户
        ClientUser user = clientUserService.getByAccount(loginRequest.getUsername());
        
        // 用户不存在
        if (user == null) {
            return Result.error(401, "用户名或密码错误");
        }
        
        // 验证密码
        if (!clientUserService.verifyPassword(loginRequest.getPassword(), user.getPassword())) {
            return Result.error(401, "用户名或密码错误");
        }
        
        // 生成token
        String token = jwtUtil.generateToken(user.getAccount());
        
        // 将token存入Redis，设置过期时间为24小时
        String redisKey = "token:" + user.getAccount();
        redisTemplate.opsForValue().set(redisKey, token, 24, TimeUnit.HOURS);
        
        // 构建响应
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        
        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAccount(user.getAccount());
        userInfo.setType(user.getType());
        
        loginResponse.setUser(userInfo);
        
        return Result.success(loginResponse);
    }
} 